Uec3.SaleEditWin = Ext.extend(Ext.UecWindow,{

	expressDeleteIds : [],
	
	saleItemDeleteIds:[],
	
	expressItemDeleteIds:[],
	
	addressFieldNames : ['areaId', 'province', 'city', 'district','street', 'postCode', 'receiverName', 'phone', 'mobile'],
	
	readOnlyFieldNames :['partnerIdBySeller','ordersId','gmtRealDelivery','memoOfSeller','address','transportType'],
	
	constructor : function(config){
	
		this.params = config.params||{},
		
		this.transportTypeCombo = Uec3.App.dictionary.getCombo("transportType",{fieldLabel:'运输方式',hiddenName:'transportType',grid:[6,2,6,2],showWhole:true});
		
		this.partSourceCombo = Uec3.App.dictionary.getCombo("part_source",{hiddenName:'source'});
		
		this.partnerCombo = getPartnerLookup(0,{grid:[2,1,2,1],allowBlank : false});
		
		this.partnerAddCombo = getPartnerAddLookup(this.partnerCombo,{emptyText : '选择客户收货地址...',grid:[2,2,4,2]});
		
		this.orderIdCombo = getOrderIdLookup('codeOfSeller',{grid:[4,1,4,1],triggerTags : [{moduleId: 'saleOrderQueryWindowCreator',triggerClass:'x-form-search-trigger',params:{partnerCmb : this.partnerCombo}}]});
		
		this.addExpreeTabButton = new Ext.Button({text : '增加急件单',iconCls : 'icon-add',scope:this,handler:this.addTab});
		
		this.northPanel = new Ext.FormPanel({
			frame : true,
			region : 'north',
			width:'100%',			
			height:130,
			items:[
				{
					layout:'uec3grid',
					layoutConfig:{
						hGrid:[6,17,54,6,17],
						vGrid:[55,45]					  	
					},
					height:45,
					items:[
						{xtype:'label',text:'销售出库单',style: {textAlign : 'center',font:'bold 20px arial,serif'},grid:[3,1,3,1]},
						{xtype:'label',text : '单据号:',grid:[4,1,4,1]},
						{xtype : 'textfield',name:'codeOfSeller',readOnly :true,style:{background:'#dddddd'},grid:[5,1,5,1]},
						{html:'<hr color="#34A4E0" />',grid:[1,2,5,2]}
					]
				},{
					layout:'uec3grid',
					layoutConfig:{
						hGrid:[6,31,6,17,6,15,4,15],
						vGrid:[50,50]					  	
					},
					height:50,
					items:[
						{xtype:'label',text:'客户:',grid:[1,1,1,1]},
						this.partnerCombo,
						{xtype:'label',text:'销售订单:',grid:[3,1,3,1]},
						this.orderIdCombo,
						{xtype:'label',text:'发货日期:',grid:[5,1,5,1]},
						{xtype:'datefield',name:'gmtRealDelivery',format:'Y-m-d H:i:s', allowBlank:false,grid:[6,1,6,1]},
						{xtype:'label',text:'备注:',grid:[7,1,7,1]},
						{xtype:'textarea',autoScroll:true,name:'memoOfSeller',grid:[8,1,8,2]},
						{xtype:'label',text:'收货地址:',grid:[1,2,1,2]},
						this.partnerAddCombo,
						{xtype:'label',text:'运输方式:',grid:[5,2,5,2]},
						this.transportTypeCombo,
						{xtype:'hidden',name:'areaId'},
						{xtype:'hidden',name:'province'},
						{xtype:'hidden',name:'city'},
						{xtype:'hidden',name:'district'},
						{xtype:'hidden',name:'street'},
						{xtype:'hidden',name:'receiverName'},
						{xtype:'hidden',name:'phone'},
						{xtype:'hidden',name:'mobile'},
						{xtype:'hidden',name:'postCode'},
						{xtype:'hidden',name:'id'},
						{xtype:'hidden',name:'buyerId'},
						{xtype:'hidden',name:'status'}
					]
				},this.addExpreeTabButton
			]
		});
		
		this.saleOrder_grid_store = new Ext.data.JsonStore({
			 root: "",
             fields:['partId','name','code','source','brand','carModel','quantity','pickedQuantity','price','origin','measurementUnit','ordersItemId']
		});		
		
		var saleOrder_grid_colName = new Ext.grid.ColumnModel({
			 columns:[new Ext.grid.RowNumberer(),
			 	{
			 	 header:'出货操作',
			 	 xtype:'anchorcolumn',
			 	 dataIndex:'partId',
			 	 width:130,
			 	 items:[
			 	 	{text:'库存出货',scope:this,handler:this.inventorySale},
			 	 	{text:'急件出货',scope:this,handler:this.expressSale}
			 	 ]
			 	},
	       		{header:'零件编码',dataIndex:'code',css:'background-color:#dddddd;',width:120},
	       		{header:'零件名称',dataIndex:'name',css:'background-color:#dddddd;',width:130},
	       		{header:'来源',dataIndex:'source',css:'background-color:#dddddd;',renderer:Ext.util.Format.comboRenderer(this.partSourceCombo)},
	       		{header:'品牌',dataIndex:'brand'},
	       		{header:'车型',dataIndex:'carModel',css:'background-color:#dddddd;'},
	       		{header:'单位',dataIndex:'measurementUnit',css:'background-color:#dddddd;'},
	       		{header:'销售数量',dataIndex:'quantity',css:'background-color:#dddddd;'},
	       		{header:'已拣数量',dataIndex:'pickedQuantity',css:'background-color:#dddddd;'},
	       		{header:'销售价',dataIndex:'price',css:'background-color:#dddddd;'},	       		
	       		{header:'产地',dataIndex:'origin'}		   		
	   		],
	    	defaults: {
          		sortable: false,
          		menuDisabled: true,
          		width:80
       		}
		});
		
		this.saleOrder_grid = new Ext.grid.EditorGridPanel({
			height:280,
			viewConfig:
			{
				scrollOffset:20,
				getRowClass : function(record,rowIndex,rowParams,store){
					//禁用数据显示红色					
					if(record.get('quantity')!=record.get('pickedQuantity')){
						return 'x-grid-record-red';
					}else{
						return  '';
					}
				}
			},	   	      
			autoScroll : true,
			titleCollapse:true,
			clicksToEdit:1,
			colModel:saleOrder_grid_colName,
			selModel:new Ext.grid.RowSelectionModel({moveEditorOnEnter:true,singleSelect :true}),
			store:this.saleOrder_grid_store,	           
			columnLines :true	       
		});
		
		this.inventorySale_grid_store = new Ext.data.JsonStore({
			root : '',
			fields : [
				{name : 'id'}, {name : 'saleId'},{name : 'partId'},{name : 'ordersItemId'},{name : 'carModel'},{name : 'documentCode'},{name : 'code'},
				{name : 'source'},{name : 'sourceName'},{name : 'name'},{name : 'measurementUnit'},{name : 'brand'},
				{name : 'origin'},{name : 'storeId'}, {name : 'storePyCode'},{name : 'storeName'},{name : 'shelf'},
			    {name : 'inventoryIdBySeller'}, // -- 卖方的零件库存ID			
				{name : 'price'}, // -- 售价
		        {name : 'orderQuantity'}, // -- 订购单上的数量(订购单的QUANTITY字段)
		        {name : 'quantity'}, // -- 实际数量
		        {name : 'retailAmount'} // --销售金额
			]
		});
		
		this.inventorySale_grid_colName = new Ext.grid.ColumnModel({
			columns : [new Ext.grid.RowNumberer(),
		    	{header : '批次',dataIndex : 'documentCode',width:130},
				{header : '零件编码',dataIndex : 'code',width:150},
				{header : '零件名称',dataIndex : 'name',width:130},				
				{header : '来源',dataIndex : 'sourceName'},
				{header : '车型',dataIndex:'carModel'},
				{header : '单位',dataIndex : 'measurementUnit'},
				{header : '订购数量',dataIndex : 'orderQuantity'},
				{header : '出库数量',dataIndex : 'quantity',editor : new Ext.form.TextField({allowBlank : false})},
				{header : '销售价',dataIndex : 'price',editor : new Ext.form.TextField({allowBlank : false})},
				{header : '销售金额',dataIndex : 'retailAmount',renderer:function(value, params, record){
                                             return record.data.quantity * record.data.price;}},
				{header : '品牌',dataIndex : 'brand'},
				{header : '产地',dataIndex : 'origin'},
				{header : '仓库',dataIndex : 'storeName'},
				{header : '仓位',dataIndex : 'shelf'}],
				defaults: {
                     sortable: false,
                     menuDisabled: true,
                     width:120
                }
		});
		
		this.inventorySale_gridButton = new Ext.app.ModuleToolbar({			
			items:[
				 {text : '添加',iconCls : 'icon-add',itemId:'addItemButton',scope:this,
			      handler:function(){
			        Uec3.App.getDesktop().launchWindowByParam("pickInventory",{record:'',inventoryStore:this.inventorySale_grid_store,scope:this,callback:this.pickInventoryCallBack});
		         }},
		         {text : '删除',iconCls : 'icon-del',itemId:'deleteItemButton',scope:this,handler:this.delItemHandler}]
		});
		
		this.inventorySale_grid = new Ext.grid.EditorGridPanel({
			viewConfig:{scrollOffset:20},	   	   
			autoScroll : true,
			titleCollapse:true,
			clicksToEdit:1,
			colModel:this.inventorySale_grid_colName,
			selModel:new Ext.grid.RowSelectionModel({moveEditorOnEnter:true,singleSelect :true}),
			store:this.inventorySale_grid_store,	           
			columnLines :true,	
			tbar:this.inventorySale_gridButton
		});
		
		this.centerPanel = new Ext.TabPanel({
			resizeTabs:true,
			tabWidth:100,
			enableTabScroll:true,
			minTabWidth:100,
			forceLayout:true,					
			region :'center',
			width:"100%",
			defaults : {autoScroll : false},
			activeTab :1,
			layoutOnTabChange:true,
			deferredRender :true,
			items:[
				{title : '订单内容',iconCls: 'tabs',layout:'fit',items:[this.saleOrder_grid],closable : false},
				{title:'库存件',iconCls:'tabs',layout:'fit',items:[this.inventorySale_grid],closable:false}
			]
		});
		
		this.southPanel = new Ext.FormPanel({
			labelAlign:'left',
			region :'south',
			height:65,
			frame:true,
			items:[
				{
					layout:'uec3grid',
					layoutConfig:{
						hGrid:[6,7,5,7,6,7,5,7,6,7,5,7,6,7,5,7],
						vGrid:[100]					  	
					},
					height:26,
					defaultType:'textfield',
					items:[
						{xtype:'label',text:'订单状态:',grid : [1, 1, 1, 1]},
						{name:'statusName',readOnly:true,style:{background:'#dddddd'},grid : [2,1,2,1]},
						{xtype:'label',text:'创建人:',grid : [3, 1, 3, 1]},
						{name:'creatorName',readOnly:true,style:{background:'#dddddd'},grid : [4,1,4,1]},
						{xtype:'label',text:'创建时间:',grid : [5, 1, 5, 1]},
						{name:'gmtCreate',readOnly:true,style:{background:'#dddddd'},grid : [6,1,6,1]},
						{xtype:'label',text:'提交人:',grid : [7, 1, 7, 1]},
						{name:'submitterName',readOnly:true,style:{background:'#dddddd'},grid : [8,1,8,1]},
						{xtype:'label',text:'提交时间:',grid : [9, 1, 9, 1]},
						{name:'gmtSubmit',readOnly:true,style:{background:'#dddddd'},grid : [10,1,10,1]},
						{xtype:'label',text:'审核人:',grid : [11, 1, 11, 1]},
						{name:'deliveryerName',readOnly:true,style:{background:'#dddddd'},grid : [12,1,12,1]},
						{xtype:'label',text:'审核时间:',grid : [13, 1, 13, 1]},
						{name:'gmtDelivery',readOnly:true,style:{background:'#dddddd'},grid : [14,1,14,1]},
						{xtype:'label',text:'总金额:',grid : [15, 1, 15, 1]},
						{name:'amount',readOnly:true,style:{background:'#dddddd'},grid : [16,1,16,1]}
					]				
				}
			]		
		});
		
		config = Ext.apply(config||{},{items:[this.northPanel,this.centerPanel,this.southPanel]});
		
		Uec3.SaleEditWin.superclass.constructor.call(this,config);	
	
	},
	
	 //private
	initComponent:function(){
		Uec3.SaleEditWin.superclass.initComponent.call(this);
	},
	
	//private 
	initEvents : function(){
		var module = this;
		Uec3.SaleEditWin.superclass.initEvents.call(this);
		this.on('show',this.winAfterShow,this);
		this.partnerCombo.on('select',module.selectPartnerComb,module);
		this.partnerCombo.on('lookupChange',module.lookupChangePartnerComb,module);
		this.partnerCombo.on('lookupClear',module.resetWholeRecord,module);
		this.partnerAddCombo.on('lookupChange',module.fillPartnerAddressInfo,module);
		this.partnerAddCombo.on('lookupClear',module.clearPartnerAddressInfo,module);
		this.orderIdCombo.on('lookupChange',module.lookupchangeOrderIdComb,module);
		this.orderIdCombo.on('lookupClear',module.lookupClearOrderIdComb,module);
	},
	
	selectPartnerComb : function(lookup, record, index){
		if(lookup.getValue() && (lookup.getValue() + '').trim() != '' && lookup.getValue() != record.data.id ) {
			Ext.MessageBox.confirm("提示", '确定更改客户?',function(btnId){
				if(btnId == "no"){
					return;
				}else{
					if(this.orderIdCombo.getValue() && (this.orderIdCombo.getValue()+'').trim() != ''){
						this.resetPartner();						
					}					
					lookup.setValue(record.data[lookup.valueField], record.data[lookup.lookupField]);
					this.setParamForField(record);
				}
			});
		}else if(!lookup.getValue()){
			lookup.setValue(record.data[lookup.valueField], record.data[lookup.lookupField]);
			this.setParamForField(record);
		}
	},
	
	lookupChangePartnerComb : function(record, creator, oldValue, win){
		if(oldValue && (oldValue + '').trim() != '' && record.data.id != oldValue ){
			Ext.MessageBox.confirm("提示", '确定更改客户?',function(btnId){
				if(btnId == "no"){
					return;
				}else{
					if(this.orderIdCombo.getValue() && (this.orderIdCombo.getValue()+'').trim() != ''){
						this.resetPartner();						
					}
					creator.setLookupValue(record.data, win);
					this.setParamForField(record);
				}
			});
		}else if(!oldValue){
			creator.setLookupValue(record.data, win);
			this.setParamForField(record);
		}
	},
	resetWholeRecord : function(){
		Ext.MessageBox.confirm("提示","确定删除该客户?",function(btnId){
			if(btnId == 'yes'){
				this.clearAllTabel();
			}				
		},this);
	},
	
	clearAllTabel : function(){
		var myMask = new Ext.LoadMask(this.el,{msg : "处理中,请稍后...."});
    	myMask.show();
    	this.partnerCombo.clearValue();
    	this.resetPartner();
    	myMask.hide();
	},
	/**
	 * 无引用订单下切换客户
	 */
	resetPartner:function(){
		this.orderIdCombo.clearValue();
		this.partnerAddCombo.clearValue();	               				
		this.northPanel.getForm().findField('gmtRealDelivery').setValue('');
		this.northPanel.getForm().findField('transportType').setValue('');	 
		this.northPanel.getForm().findField('memoOfSeller').setValue('');
		this.southPanel.getForm().reset();
		this.clearPartnerAddressInfo();
		this.removeExpressTab();
		this.addItemButton();              				
		this.saleOrder_grid_store.removeAll();
		this.inventorySale_grid_store.removeAll();	               				
		this.centerPanel.hideTabStripItem(0);
		this.centerPanel.setActiveTab(1);		
	},
	
	setParamForField : function(record){
		this.northPanel.getForm().findField("buyerId").setValue(record.data.companyId);
	},
	
	fillPartnerAddressInfo : function(record){
		Ext.each(this.addressFieldNames, function(fieldName, index, array) {
			if (record.data) {
				this.northPanel.getForm().findField(fieldName).setValue(record.data[fieldName]);
			} else {
				this.northPanel.getForm().findField(fieldName).setValue(record[fieldName]);
			}
		},this);
	},
	
	clearPartnerAddressInfo : function(){
		Ext.each(this.addressFieldNames, function(fieldName, index, array) {			
			this.northPanel.getForm().findField(fieldName).reset();				
		},this);
	},
	
	clearSpecifyField : function(fieldArr){
		Ext.each(fieldArr, function(fieldName, index, array) {			
			this.northPanel.getForm().findField(fieldName).reset();				
		},this);
	},
	
	removeExpressTab : function(){
		var items = this.centerPanel.items.items;
		for(var i = items.length;i > 0;i--){
			if(i > 1){
				this.centerPanel.remove(items[i]);
			}
		}	
	},
	
	/**
	 * 库存件panel增加按钮
	 */
	addItemButton : function(){
		var addItemButton = this.inventorySale_gridButton.getComponent('addItemButton')
    	if(Ext.isEmpty(addItemButton)){
        	this.inventorySale_gridButton.add({
            	text : '添加',iconCls : 'icon-add',itemId:'addItemButton',scope:this,
                handler:function(){
                	Uec3.App.getDesktop().launchWindowByParam("pickInventory",{record:'',inventoryStore:this.inventorySale_grid_store,scope:this,callback:this.pickInventoryCallBack});
                }
            });	               				
        }
        this.inventorySale_gridButton.doLayout();
	},
	/**
	 * 引用未被处理为销售出库单的销售订单后,删除库存件面添加按钮,所有急件面板
	 */
	removeAddItemButton : function(){
		var addItemButton = this.inventorySale_gridButton.getComponent('addItemButton');
		if(!Ext.isEmpty(addItemButton)){
			this.inventorySale_gridButton.remove(addItemButton);
		}
	},
	
	lookupchangeOrderIdComb : function(record){
		var id= record.data.id;
   	  	if(Ext.isEmpty(id)){
   	  		Ext.MessageBox.alert("提示","请确定是否确定引用销售订单!");
   	  	}else{ 	  		
			this.initSaleAndItemsByOrderId(id);
			this.removeAddItemButton();
   	  	}
	},
	lookupClearOrderIdComb : function(){
		Ext.MessageBox.confirm("提示","确定删除该销售订单号?",function(btnId){
			if(btnId == "yes"){
				this.orderIdCombo.clearValue();
				this.removeExpressTab();	               				
				this.saleOrder_grid_store.removeAll();
				this.inventorySale_grid_store.removeAll();
				this.centerPanel.hideTabStripItem(0);
				this.centerPanel.setActiveTab(1);
				this.southPanel.getForm().reset();
				this.clearSpecifyField(['id','status','gmtRealDelivery','memoOfSeller']);
				this.transportTypeCombo.clearValue();
				this.addItemButton();            				
			}
		},this);
	},
	/**
	 * 增加急件销售面板
	 */
	addTab : function(){
		var toolBar = this.getToolBar4Exp();
		var partner_combox = getPartnerLookup(1,{grid:[2,1,2,1],itemId:'express_partnerComb',allowBlank : false});
		//急件store
		var urgentSale_store = new Ext.data.JsonStore({
			root : '',
			fields : ['id','expressId','partId','code','source','sourceName','name','carModel','measurementUnit','brand',
					  'origin','storeId','storePyCode','storeName','shelf',			
					  {name : 'inventoryIdBySeller'}, // -- 卖方的零件库存ID(入库后产生这个ID)				
					  {name : 'cost'}, // -- 进价
					  {name : 'retailPrice'}, // --售价
					  {name : 'insurancePrice'}, // --保险价
					  {name : 'minPrice'}, // -- 最低售价
					  {name : 'buyQuantity'}, // -- 买入数量
				      {name : 'saleQuantity'}, // -- 卖出数量
					  {name : 'retailAmount'}, // --销售金额
					  {name : 'costAmount'}, // --进价金额
					  {name : 'retailAmount'} // --销售金额
				]
		});
	
		var urgentSale_grid = new Ext.grid.EditorGridPanel({
			frame : false,	
			viewConfig : {scrollOffset:20},
			region: 'center',
			store : urgentSale_store,							
			itemId : 'id_urgentSale_grid',
			tbar:toolBar,
			columns : [
				new Ext.grid.RowNumberer(),
				{header : '零件编码',dataIndex : 'code'},
				{header : '零件名称',dataIndex : 'name'},
				{header : '车型',dataIndex:'carModel'},
				{header : '来源',dataIndex : 'sourceName'},
				{header : '单位',dataIndex : 'measurementUnit'},
				{header : '买入数量',dataIndex : 'buyQuantity'},
				{header : '销售数量',dataIndex : 'saleQuantity',editor : new Ext.form.TextField({allowBlank : false})},
				{header : '销售价',dataIndex : 'retailPrice',editor : new Ext.form.TextField({allowBlank : false})},
				{header : '销售金额',dataIndex : 'retailAmount',renderer:function(value, params, record){
			                 return record.data.saleQuantity * record.data.retailPrice;}
			    },
				{header : '品牌',dataIndex : 'brand'},
				{header : '产地',dataIndex : 'origin'},
				{header : '仓库',dataIndex : 'storeName'},
				{header : '仓位',dataIndex : 'shelf'}],
			sm : new Ext.grid.RowSelectionModel({singleSelect : true}),
			columnLines : true,
			enableHdMenu : false,			
			stripeRows : true,
			autoScroll : true
		});
		
		var urgentSaleForm = new Ext.FormPanel({
			frame : true,							
			itemId : 'urgentSaleForm',
			region: 'north',
			height : 40,
			layout:'uec3grid',
			layoutConfig:{
				hGrid:[4,32,8,15,4,37],
				vGrid:[100]
			},
			items:[
				{xtype : 'label',text : '卖方:',grid:[1,1,1,1]}, partner_combox, 
				{xtype : 'label',text : '卖方单据号:',grid:[3,1,3,1]},
				{xtype : 'textfield',name : 'codeOfSeller',grid:[4,1,4,1]}, 
				{xtype : 'label',text : '备注:',grid:[5,1,5,1]},
				{xtype : 'textfield',name:"memo",grid:[6,1,6,1]},
				{xtype : 'hidden',name : 'sellerId'}, 
				{xtype : 'hidden',name : 'id'}
			]
		});
		
		this.regEvent4PartnerLookup(partner_combox,urgentSaleForm);
		
		var tabs = this.centerPanel;
		var win = this;
		tabs.add({
			title : '急件单(' + (this.centerPanel.items.length-1) + ')',
			iconCls : 'tabs',
			layout:'border',
			items : [urgentSaleForm,urgentSale_grid],
			closable : true,			
			listeners:{
			   'close':function(panel){
			       var id = urgentSaleForm.getForm().findField("id").getValue();
			  	   if(!Ext.isEmpty(id)){
			  	      win.expressDeleteIds.push(id);
			  	   }
			  	   if(win.centerPanel.get(0).isVisible()){
			  	   		var expRecords = urgentSale_store.getRange();
			  	   		Ext.each(expRecords,function(expRecord,index){
			  	   			var orderIndex = win.saleOrder_grid_store.findExact('partId',parseInt(expRecord.get('partId')));
			  	   			if(orderIndex != -1){
			  	   				var orderRecord = win.saleOrder_grid_store.getAt(orderIndex);
			  	   				var pickQty = orderRecord.get('pickedQuantity')-expRecord.get('buyQuantity');
			  	   				orderRecord.set('pickedQuantity',pickQty);
			  	   				win.saleOrder_grid.getView().refresh();
			  	   			}
			  	   		});
			  	   }
			     }			     
			}
		}).show();
		
		tabs.doLayout();
		tabs.setActiveTab(tabs.items.length-1);
		return tabs.get(tabs.items.length-1);
	},
	
	regEvent4PartnerLookup : function(partnerLookup,urgentSaleForm){
		partnerLookup.on('select',function(lookup,record,index){
			lookup.setValue(record.data[lookup.valueField], record.data[lookup.lookupField]);
			urgentSaleForm.getForm().findField('sellerId').setValue(record.data.companyId);
		});
		partnerLookup.on('lookupChange',function(record, creator, oldValue, win){
			creator.setLookupValue(record.data, win);
			urgentSaleForm.getForm().findField('sellerId').setValue(record.data.companyId);
		});
		partnerLookup.on('lookupClear',function(){
			partnerLookup.clearValue();
			urgentSaleForm.getForm().findField('sellerId').reset();
		});
	},
	
	getToolBar4Exp : function(){
		var orderId = this.orderIdCombo.getValue();
		var toolBar;
		var deleteBar = {text : '删除',iconCls : 'icon-del',itemId:'deleteItemButton',scope:this,handler:this.delItemHandler};
		if(Ext.isEmpty(orderId)){
			toolBar = new Ext.Toolbar({
			  	items:[
					{text : '添加',iconCls : 'icon-add',itemId:'addItemButton',scope:this,handler:this.addExpressItemHandler},				
					deleteBar
			    ]
			});
		}else{
			toolBar = new Ext.Toolbar({
			  	items:[deleteBar]
			});
		}
		
		return toolBar;
	},
	
	/**
	 * 库存出货
	 */
	inventorySale : function(grid, rowIndex, colIndex, item, e){
		var record = grid.getStore().getAt(rowIndex);
		Uec3.App.getDesktop().launchWindowByParam("pickInventory",{record:record,inventoryStore:this.inventorySale_grid_store,callback:this.pickInventoryCallBack,scope:this});
	},
	
	pickInventoryCallBack : function(data,hasOrder,differentQty){							
	 	if(hasOrder){
	 		var index = this.saleOrder_grid_store.findExact('code',data.get('code'));
			var orderRecord = this.saleOrder_grid_store.getAt(index);
			var opQty = Ext.isEmpty(orderRecord.get('pickedQuantity')) ? 0 : parseInt(orderRecord.get('pickedQuantity'));
			var dQty = Ext.isEmpty(differentQty) ? 0 : parseInt(differentQty);
			var pickQuantity = opQty + dQty;
			var quantity = parseInt(orderRecord.get('quantity'));
			if(pickQuantity > quantity){
				Ext.MessageBox.alert('提示','已拣数量不能大于订购数量!');
				return false;
			}else{
				orderRecord.set('pickedQuantity',pickQuantity);
			}			
	 	}
	 	var inventIndex = this.inventorySale_grid_store.findExact('inventoryIdBySeller',data.get('inventoryIdBySeller'));
	 	if(inventIndex == -1){
			this.inventorySale_grid_store.add(data);
		}else{
			var inventRecord = this.inventorySale_grid_store.getAt(inventIndex);
			inventRecord.set('quantity',data.get('quantity'));
		}
		return true;
	},
	/**
	 * 急件出货
	 */
	expressSale : function(grid, rowIndex, colIndex, item, e){
		var record = grid.getStore().getAt(rowIndex);
		Uec3.App.getDesktop().launchWindowByParam("pickExpress",{record:record.data,scope:this,callback:this.pickExpressCallBack});				
	},
	
	pickExpressCallBack : function(data,hasOrder){
		if(hasOrder){
			var index = this.saleOrder_grid_store.findExact('code',data.code);
			var orderRecord = this.saleOrder_grid_store.getAt(index);
			var quantity = orderRecord.get('quantity');
			var opQty = Ext.isEmpty(orderRecord.get('pickedQuantity')) ? 0:parseInt(orderRecord.get('pickedQuantity')) ;
			var sQty =  Ext.isEmpty(data.saleQuantity) ? 0 : parseInt(data.saleQuantity);
			var pickQuantity = opQty + sQty;
			if(pickQuantity > quantity){
				Ext.MessageBox.alert('提示','已拣数量不能大于订购数量!');
				return;
			}else{
				orderRecord.set('pickedQuantity',pickQuantity);
			}
		}
		var tab = this.findExpTab(data.partnerId);
		if(Ext.isEmpty(tab)){
			tab = this.addTab();
		}
		var express_form = tab.getComponent("urgentSaleForm");
	    var express_store = tab.getComponent("id_urgentSale_grid").getStore();
	    var index =  express_store.findExact('partId',parseInt(data.partId));
	    if(index == -1){
	    	express_store.add(new Ext.data.Record(data));
	    }else{
	    	var expressRecord = express_store.getAt(index);
	    	expressRecord.set('buyQuantity',data.buyQuantity);
	    	expressRecord.set('saleQuantity',data.saleQuantity);
	    }	
		express_form.getForm().setValues(data);
		express_form.getComponent('express_partnerComb').initializeValue({'name':data.partnerName,'pyCode':data.partnerPyCode,'id':data.partnerId});
	},
	
	findExpTab:function(partnerId){
		var items = this.centerPanel.items.items;
		var reActTab;
		Ext.each(items,function(item,index,items){
			if(index > 1){
			    this.centerPanel.setActiveTab(index);
				var actTab = this.centerPanel.getActiveTab();
				var expForm = actTab.getComponent("urgentSaleForm");
				var expRecords = actTab.getComponent("id_urgentSale_grid").getStore().getRange();
				var express = encodeFilte(expForm.getForm().getValues());
				if(Ext.isEmpty(express.partnerIdByBuyer)&&Ext.isEmpty(express.codeOfSeller)&&Ext.isEmpty(express.memo)){
					if(Ext.isEmpty(expRecords)){
						reActTab=actTab
						return false;
					}else{
						return false;
					}
				}else{
					var partnerIdByBuyer = express.partnerIdByBuyer;
					if(!Ext.isEmpty(partnerId)&&partnerId == partnerIdByBuyer){
						reActTab=actTab
						return false;
					}
					return false;
				}
			}
		},this);
		return reActTab;
	},
	
	/**
	 * 增加急件tab的添加toolbar
	 */
	addExpressItemHandler : function(){
		var expTab = this.centerPanel.getActiveTab();
		var expForm = expTab.getComponent('urgentSaleForm');
		var expGrid = expTab.getComponent('id_urgentSale_grid');
		var partner_combox = expForm.getComponent('express_partnerComb');
		var ds_partner_store = partner_combox.getStore();
		var record = expForm.getForm().getValues();
		var index = ds_partner_store.findExact("id",record.partnerIdByBuyer);
		var pRrcord = ds_partner_store.getAt(index);
		var partnerName,partnerPyCode;
		if(Ext.isEmpty(pRrcord)){
		    partnerName = partner_combox.getRawValue();
		    partnerPyCode = partner_combox.lookupValue;
		}else{
			partnerName = pRrcord.get("name");
			partnerPyCode = pRrcord.get("pyCode");
		}
		record.partnerName = partnerName;
		record.partnerPyCode = partnerPyCode;
		Uec3.App.getDesktop().launchWindowByParam("pickExpress",{record:record,scope:this,callback:this.pickExpressCallBack});
	},
	/**
	 * 删除出库明细,库存销售&急件销售
	 */
	delItemHandler : function(isFormPick){
		var tab = this.centerPanel.getActiveTab();
		var grid;
		if (tab.title == "库存件") {
			grid = this.inventorySale_grid;
		} else {
			grid = tab.getComponent("id_urgentSale_grid");
		}
		var record = grid.getSelectionModel().getSelected();
		if (record) {
			if(isFormPick){
				this.deleteItemByCondition(record,grid);
			}else{
				Ext.Msg.confirm('确认删除', '你确定删除该条记录?', function(btn) {
					if (btn == 'yes') {
						this.deleteItemByCondition(record,grid);
					}
				},this);
			}			
		} else {
			Ext.MessageBox.alert("提示", "请选择要删除的记录!");			
		}
	},
	
	deleteItemByCondition : function(record,grid){
		var id = record.data.id;
		var expressId = record.data.expressId;
		var saleId = record.data.saleId;
		var partId = record.data.partId;
		var deletNum = record.data.quantity||record.data.saleQuantity;
		var store = grid.getStore();
		store.remove(record);
	
		if (id && saleId) {
			this.saleItemDeleteIds.push({id : id,saleId : saleId});
		}
		if (id && expressId) {
			this.expressItemDeleteIds.push({id : id,expressId : expressId});
		}
		var index = this.saleOrder_grid_store.findExact('partId',partId);
		if(index != -1){
			var orderRecord = this.saleOrder_grid_store.getAt(index);
			var num = parseInt(orderRecord.get('pickedQuantity'))-parseInt(deletNum);
			orderRecord.set('pickedQuantity',num);
			this.saleOrder_grid.getView().refresh();
		}
	},
	
	initialButtons : function(){
		var myMask = new Ext.LoadMask(this.el,{msg : "按钮加载中,请稍候...."});
        myMask.show();
        Ext.Ajax.request({
			url : Uec3.App.Constants.homeUrl+ "/sale/saleInitButton!getSaleInitButtons.do",
			method:'get',
			callback : function(options, success, response) {
				myMask.hide();
			},
			success : function(response, options) {
				var resp = Ext.decode(response.responseText);
				var buttons = resp.buttons;
				this.addButtonPanel(buttons,this.southPanel);
			},
			failure : function(response, options) {
				Ext.MessageBox.alert("提示", "初始化按钮出错!");
			},
			scope : this
		});
	},
	
	initSaleAndItemsById : function(id){
		var myMask = new Ext.LoadMask(this.el,{msg : "正在加载销售出库单,请稍后....."});
      	myMask.show();
		Ext.Ajax.request({
			url : Uec3.App.Constants.homeUrl+ "/sale/toSale!getSaleAndItemsById.do",
			params : {queryParam:id},
			callback : function(options, success, response) {
				myMask.hide();
			},
			success : function(response, options) {
				var data = Ext.decode(response.responseText);
				this.fillMainContent(data);									     
				changeWindowUecId(data.sale.codeOfSeller,this.params.uecId);
			},
			failure : function(response, options) {
				Ext.MessageBox.alert("提示", "网络异常,加载单据失败!");
			},
			scope : this
		});
	},
	
	initSaleAndItemsByOrderId : function(orderId){
		var myMask = new Ext.LoadMask(this.el,{msg : "正在处理中,请稍后....."});
      	myMask.show();
		Ext.Ajax.request({
			url :Uec3.App.Constants.homeUrl+"/sale/orderForSale!getOrderDetailForSale.do",
			params :{queryParam:orderId},
			method :"post",
			callback :function(options,success,response){				
				myMask.hide();					
			},
			success:function(response,options){
				var data = Ext.decode(response.responseText);
				if(data.success){
					if(data.hasSale){
						this.fillMainContent(data);							
					}else{						
						Ext.MessageBox.confirm("提示",data.msg.confirm,this.readyToHandelOrder,this)
					}
				}else{
					Ext.MessageBox.alert("提示",data.msg);
				}										
			},
			failure:function(response,options){
				Ext.MessageBox.alert("提示","网络异常");
			},
			scope:this
		});
	},
	
	readyToHandelOrder : function(btnId){
		if(btnId == 'yes'){
			var ordersId = this.orderIdCombo.getValue();
			var myMask = new Ext.LoadMask(this.el,{msg : "正在接手销售订单,请稍后....."});
			myMask.show();
			Ext.Ajax.request({
				url:Uec3.App.Constants.homeUrl+"/sale/acceptOrderToSale.do",
				params :{queryParam:ordersId},
				method :"post",
				callback :function(options,success,response){
					myMask.hide();      
				},
				success : function(response,options){
					var data = Ext.decode(response.responseText);
					if(data.success){
						this.centerPanel.unhideTabStripItem(0);
						this.centerPanel.setActiveTab(0);
						var sale_main = data.order;
						this.orderIdCombo.initializeValue({'id':sale_main.ordersId,'codeOfSeller':sale_main.codeOfSeller})
						delete sale_main.codeOfSeller;
						//显示sale主表						
						this.northPanel.getForm().setValues(sale_main);
						this.partnerCombo.initializeValue({'name':sale_main.partnerNameBySeller,'pyCode':sale_main.partnerPyCodeBySeller,'id':sale_main.partnerIdBySeller});
						this.partnerAddCombo.initializeValue({'areaId':sale_main.areaId,'address':sale_main.province+sale_main.city+sale_main.district+sale_main.street+","+sale_main.receiverName+","+sale_main.phone+","+sale_main.mobile});																			
						//客户地址的隐藏框填值
						this.fillPartnerAddressInfo(sale_main);
						//显示订单明细								
						this.saleOrder_grid_store.loadData(data.orderItem);						
						this.initialButtons();
					}else{
						Ext.MessageBox.alert("提示",data.msg);
					}
				},
				failure : function(response,options){
					Ext.MessageBox.alert("提示","网络连接异常,请稍候处理!");
				},
				scope:this
			});
		}
	},
	
	fillMainContent : function(data){
		this.removeExpressTab();
		//sale主表
		var sale_main = data.sale;
		//saleItem
		var saleItem_data = data.saleItem;
		//express主表及expressItem
		var expressAndItems = data.express;
		//按钮
		var buttons = data.buttons.buttons;
		//是否单据所有者
		var isOwner = data.buttons.isOwner;
		//msg
		var msg = data.msg;
		//显示sale主表
		this.northPanel.getForm().setValues(sale_main);
		this.partnerCombo.initializeValue({'name':sale_main.partnerNameBySeller,'pyCode':sale_main.partnerPyCodeBySeller,'id':sale_main.partnerIdBySeller});
		this.partnerAddCombo.initializeValue({'areaId':sale_main.areaId,'address':sale_main.province+sale_main.city+sale_main.district+sale_main.street+","+sale_main.receiverName+","+sale_main.phone+","+sale_main.mobile});			
		this.orderIdCombo.initializeValue({'id':sale_main.ordersId,'codeOfSeller':sale_main.orderCodeOfSeller});
		this.fillPartnerAddressInfo(sale_main);
		//显示单据状态条
		this.southPanel.getForm().setValues(sale_main);
		if(data.withOrder){
			this.centerPanel.unhideTabStripItem(0);
			//this.centerPanel.setActiveTab(0);
			this.saleOrder_grid_store.loadData(data.orderItem) 
		}
		//库存件销售明细	
		this.centerPanel.setActiveTab(1);
		this.inventorySale_grid_store.loadData(saleItem_data);
		//急件销售明细
		Ext.each(expressAndItems,function(item,index){
			var express_main = item['express'];
			var expressItem_data = item['expressItem'];								
			this.addTab();
			var expressTab = this.centerPanel.getActiveTab();
			var express_form = expressTab.getComponent("urgentSaleForm");
			var expressItem_store = expressTab.getComponent("id_urgentSale_grid").getStore();
			//急件主表
		    express_form.getForm().setValues(express_main);
		    express_form.getComponent('express_partnerComb').initializeValue({'name':express_main.partnerNameByBuyer,'pyCode':express_main.partnerPyCodeByBuyer,'id':express_main.partnerIdByBuyer});
		    //急件明细
			expressItem_store.loadData(expressItem_data);			
		},this);	
		//显示相应按钮条
		this.addButtonPanel(buttons,this.southPanel);
		//判断是否所有者打开当前单据,页面不同展示效果
      	this.rendererSpecificColumnByConditon(isOwner);			       	
      	if(msg.confirm){
			this.toSaleInvoice(msg.confirm,data.receivableId,data.customerId);		  	   		
		}
      	if(msg){
      		Ext.MessageBox.alert("提示",msg);
      	}
	},
	
	toSaleInvoice : function(msg,receivableId,customerId){
		
		Ext.MessageBox.confirm("提示",msg,function(btnId){
			if(btnId == 'yes'){		  	       
				//跳转收款单页面		  	  	  
				Uec3.App.getDesktop().launchWindowByParam("saleInvoice_operation",{id:receivableId,customerId:customerId,winId:receivableId});
			}
		});
	},
	
	rendererSpecificColumnByConditon : function(isOwner){
		var status = this.northPanel.getForm().findField("status").getValue();
		if(isOwner){
			if(status == 2 || status == 1){
				this.renderCompByCon(false);
			}else{
				this.renderCompByCon(true); 
			}
		}else{
			this.renderCompByCon(false);
		}
	},
	/**
	 * 
	 * @param {} isShow,是否显示该组件
	 */
	renderCompByCon : function(isShow){
		var inventoreyView = this.inventorySale_grid.getView().mainBody;									
		var inventoreyGridMask =new Ext.LoadMaskJUPIT(inventoreyView);
		var items = this.centerPanel.items.items;
		if(isShow){
			this.setReadOnly4NPByCon(isShow,this.readOnlyFieldNames,this.northPanel);		
			this.inventorySale_grid.getTopToolbar().enable();
			this.addExpreeTabButton.enable();
			inventoreyGridMask.hide();
			Ext.each(items,function(item,index,items){
				if(index > 1){
					var expressForm = item.getComponent("urgentSaleForm");
					var expressGrid = item.getComponent("id_urgentSale_grid");
					var expressView = expressGrid.getView().mainBody;
					var expressMask = new Ext.LoadMaskJUPIT(expressView);
					this.setReadOnly4NPByCon(isShow,['partnerIdByBuyer','codeOfSeller','memo'],expressForm);
					expressGrid.getTopToolbar().enable();
					expressMask.hide();
				}
			},this);
		}else{
			this.setReadOnly4NPByCon(isShow,this.readOnlyFieldNames,this.northPanel);		
			this.inventorySale_grid.getTopToolbar().disable();
			this.addExpreeTabButton.disable();
			inventoreyGridMask.show();
			Ext.each(items,function(item,index,items){
				if(index > 1){
					var expressForm = item.getComponent("urgentSaleForm");
					var expressGrid = item.getComponent("id_urgentSale_grid");
					var expressView = expressGrid.getView().mainBody;
					var expressMask = new Ext.LoadMaskJUPIT(expressView);
					this.setReadOnly4NPByCon(isShow,['partnerIdByBuyer','codeOfSeller','memo'],expressForm);
					expressGrid.getTopToolbar().disable();				
					expressMask.show();
				}
			},this);
		}
	},	
	
	/**
	 * 根据条件设置formPanel下的某组件为readOnly
	 * @param {} readOnlyFieldNames
	 * @param {} parentCt
	 */
	setReadOnly4NPByCon : function(isShow,readOnlyFieldNames,parentCt){
		Ext.each(readOnlyFieldNames, function(fieldName, index, array) {
			var field = parentCt.getForm().findField(fieldName);
			if(isShow){
				field.setReadOnly(false);
				field.getEl().setStyle('background','');
			}else{
				field.setReadOnly(true);
				field.getEl().setStyle('background','#dddddd');
			}
		},this);
	},
	checkOrderQuantity : function(){
		var isCheck;
		if(Ext.isEmpty(this.orderIdCombo.getValue())){
			isCheck = false;
		}else{
			isCheck = this.centerPanel.get(0).isVisible()?true:false;
		}
		return isCheck;
	},
	
	getOrderPickedQty : function(){
		var orderPickedQty = [];
		var orderRecords = this.saleOrder_grid_store.getRange();
		Ext.each(orderRecords,function(record,index){
			var orderRecord = {'id':parseInt(record.get('ordersItemId')),'pickedQuantity':(Ext.isEmpty(record.get('pickedQuantity'))?0:parseInt(record.get('pickedQuantity')))};
			orderPickedQty.push(orderRecord);
		});
		return orderPickedQty;
	},
	/**
	 * 取得销售单sale，saleItem，express，expressItem
	 */
	getAllSaleInfo:function(checkQuantity) {
		if(this.northPanel.getForm().isValid()){
			var sale = this.northPanel.form.getValues();
			if(Ext.isEmpty(sale.partnerIdBySeller,false)){
				Ext.MessageBox.alert('提示','请选择客户!');	
			    return;
			}
			var orderPickedQty = [];
			if(checkQuantity){
				var orderRowIndexs = [];
				var orderRecords = this.saleOrder_grid_store.getRange();
				var isEqual = Ext.each(orderRecords,function(record,index){
					if(record.get('quantity')!=record.get('pickedQuantity')){
						Ext.MessageBox.alert('提示','订购数量与销售数量不相等,请查看红色标记记录!');
						return false;
					}
					return true;
				});
				if(isEqual){
					orderPickedQty = this.getOrderPickedQty();				
				}else{
					return;
				}
			}
			var saleItem = [];
			var expresses = [];
			var inventoryRecords = this.inventorySale_grid_store.getRange();
			for (var i = 0; i < inventoryRecords.length; i++) {
				var record = inventoryRecords[i].data;
				saleItem.push(record);
			}
			var items = this.centerPanel.items.items;
			Ext.each(items, function(item, index, items) {
				if(index > 1){
					var expressItem = [];
					//alert(index);
					this.centerPanel.setActiveTab(index);
					var express_form =this.centerPanel.getActiveTab().getComponent("urgentSaleForm");
					var express = express_form.getForm().getValues();
					var totalRecords = this.centerPanel.getActiveTab().getComponent("id_urgentSale_grid").getStore().getRange();
					for (var i = 0; i < totalRecords.length; i++) {
						var record = totalRecords[i].data;
						expressItem.push(record);
					}							
					var exp = {express : express,expressItem : expressItem};
					expresses.push(exp);
				}
			},this);
			if(Ext.isEmpty(saleItem) && Ext.isEmpty(expresses)){
		         Ext.MessageBox.alert('提示','未有出库明细!');
		         return;
		    }
		    if(this.checkOrderQuantity()){
		    	orderPickedQty = this.getOrderPickedQty();	
		    }
			var saleInfo = {sale : sale,saleItem : saleItem,express : expresses,saleItemDeletedIds : this.saleItemDeleteIds,expressItemDeletedIds :this.expressItemDeleteIds,expressDeleteIds:this.expressDeleteIds,orderPickedRecord:orderPickedQty};
			return Ext.util.JSON.encode(saleInfo);
		}			
	},
	
	create:function(btn){
		this.backupSaleAndItem(btn,"确定保存草稿?","草稿保存中,请稍后.....");
	},
		
	submit:function(btn){
		var checkQuantity = this.checkOrderQuantity();
		this.backupSaleAndItem(btn,"确定保存单据为待仓库审核状态?","待审核单据保存中,请稍后.....",checkQuantity);
	},
	
	delivery:function(btn){
	    this.backupSaleAndItem(btn,"确定出货?","出货单正在处理中,请稍后.....");
	},
	/**
	 * 重置(放弃当前编辑内容)
	 */
	reset:function(btn,msg){
		this.resetWholeSale("确定清空表单?");
	},
	
	resetWholeSale:function(msg){
		Ext.MessageBox.confirm("提示",msg,function(btnId){
			if(btnId == 'yes'){
		    	this.clearAllTabel();
		    }				
	    },this);
	},
	
	/**
	 * 浏览销售单
	 */
	saleBrowser:function(btn){
		redirectUrl("sale_browser");
	},
	/**
	 * 打印
	 */
	salePrint:function(btn){
		alert('to be continued...');
	},
	/**
	 * 返回
	 */
	exit:function(btn){			
		Ext.MessageBox.confirm("提示","确定退出?",function(btnId){
			if(btnId == 'yes'){
				this.close();
			}				
	    },this);
	},
	/**
	 * 接手单据
	 */
	acceptSale:function(btn){
		this.acceptOrReleaseSale(btn,"确定接手单据?","正在接手单据,请稍后.....");
	},
	/**
	 * 释放单据
	 */
	releaseSale:function(btn){
		this.acceptOrReleaseSale(btn,"确定释放单据?","正在释放单据,请稍后.....");
	},
	/**
	 * 删除草稿单据
	 */
	deleteCreate:function(btn){
		var saleId = this.northtPanel.getForm().findField("id").getValue();
		if(!Ext.isEmpty(saleId)){
		Ext.MessageBox.confirm("提示","确定删除出库单草稿?",function(btnId){
			if(btnId == 'yes'){
				var myMask = new Ext.LoadMask(this.el,{msg : "出库单草稿删除中,请稍后...."});
				myMask.show();
				Ext.Ajax.request({
					url:btn.url,
					params :{queryParam:saleId},
					method :"post",
					callback :function(options,success,response){
						myMask.hide();
					},
					success:function(response,options){
						var data = Ext.decode(response.responseText);
						Ext.MessageBox.alert("提示",data.msg);
						if(data.success){
							this.close();
							redirectUrl("sale_browser");
						}
					},
					failure:function(response,options){
						Ext.MessageBox.alert("提示","发生异常，请稍候处理!");    
					},
					scope:this
				});
			}				
		  },this);
		}		    
	},
	/**
	 * 退回(退回到草稿)
	 */
	backToCreate:function(btn){			
		var saleId = this.northtPanel.getForm().findField("id").getValue();
		if(!Ext.isEmpty(saleId)){
		Ext.MessageBox.confirm("提示","确认待审核销售出库单退回草稿?",function(btnId){
			if(btnId == 'yes'){
				var myMask = new Ext.LoadMask(this.el,{msg : "退回草稿中,请稍后...."});
				myMask.show();
				Ext.Ajax.request({
					url:btn.url,
					params :{queryParam:saleId},
					method :"post",
					callback :function(options,success,response){
						myMask.hide();
					},
					success:function(response,options){
						var data = Ext.decode(response.responseText);
						Ext.MessageBox.alert("提示",data.msg);
						if(data.success){
							fillMainContent(data);
						}
					},
					failure:function(response,options){
						Ext.MessageBox.alert("提示","发生异常，请稍候处理!");    
						},
						scope:this
					});
				}				
			},this);
		}		    
	},
			
	/**
	 * 新建 
	 */
	newSale:function(btn){
		 redirectUrl("sale_add");
	},
				
			    
	backupSaleAndItem:function(btn,msg,wait,checkQuantity){
		var saleInfo = this.getAllSaleInfo(checkQuantity);
		if(!Ext.isEmpty(saleInfo)){
			Ext.MessageBox.confirm("提示",msg,function(btnId){
			if(btnId == 'yes'){
				var myMask = new Ext.LoadMask(this.el,{msg :wait});
	            myMask.show();
	            Ext.Ajax.request({				
					url:btn.url,
					method :"post",					   
					params:{queryParam:saleInfo},
					callback :function(options,success,response){
		              myMask.hide();       
		            },
					success:function(response,options){
						 var data = Ext.decode(response.responseText);
						 if(data.success){					   
						    this.fillMainContent(data);			  
						    changeWindowUecId(data.sale.codeOfSeller,"sale_add","sale_add_"+data.sale.id);
						 }else{
						    Ext.MessageBox.alert("提示",data.msg);
						 }
				   },
				   failure:function(response,options){
		                Ext.MessageBox.alert("提示","发生异常，请稍候处理!");    
			           },
			           scope:this
				  });
			   }                    
		  },this);
	   }	
	},
			
	acceptOrReleaseSale:function(btn,msg,wait){
	    var saleId = this.northtPanel.getForm().findField("id").getValue();
		if(!Ext.isEmpty(saleId)){
		Ext.MessageBox.confirm("提示",msg,function(btnId){
			if(btnId == 'yes'){
				  var myMask = new Ext.LoadMask(this.el,{msg : wait});
	              myMask.show();
		          Ext.Ajax.request({
	      				url:btn.url,
	      				params :{queryParam:saleId},
	      				method :"post",
	      				callback :function(options,success,response){
	                		myMask.hide();
	     				},
	      				success:function(response,options){
				 			var data = Ext.decode(response.responseText);
				 			if(data.success){
				 				var buttons = data.buttons;
				 				var isOwner = data.isOwner;				    			
	             				// 显示相应按钮条
	               			    this.addButtonPanel(buttons,this.southPanel);
	               				this.rendererSpecificColumnByConditon(isOwner);	                    
				 		   }else{
				   				Ext.MessageBox.alert("提示",data.msg);
				 		   }
	      			    },
	      				failure:function(response,options){
	           				Ext.MessageBox.alert("提示","发生异常，请稍候处理!");    
	          				},
	          				scope:this
			        });
	    		}
	    	},this);
	    }
	},
	
	winAfterShow : function(){
		this.centerPanel.hideTabStripItem(0);
		if(this.params.id){
			this.initSaleAndItemsById(this.params.id);
		}else if(this.params.orderId){
			this.orderIdCombo.initializeValue({'id':this.params.orderId,'codeOfSeller':this.params.codeOfSeller})
		    this.initSaleAndItemsByOrderId(this.params.orderId);
		}else{
			this.initialButtons();				
		}
	}
});

Uec3.SaleEditWindow = Ext.extend(Ext.app.Module, {	
	id:'sale_add',
	createWindow : function(params) {
		var windowId='sale_add';
		if(params&&params.winId){
			windowId+=Ext.isEmpty(params.winId)?"":"_"+params.winId;
		}
		params.uecId=windowId;
		//params.app = this.app;
		var desktop = this.app.getDesktop();
		var win = desktop.getWindowByUecId(windowId);
		if (!win){ 
			win = desktop.createWindow({
				uecId:windowId,
				title : '销售出库',
				width : 1000,
				height : 500,
				params:params,
				minWidth:1000,
				minHeight:500,
				iconCls : 'acc-icon',
				maximizable : true,
				monitorResize : true,
				constrain:true,
				resizeHandles :'se',
				constrainHeader : true,
				taskbuttonTooltip : "销售出库",
				layout : "border"
			},Uec3.SaleEditWin);
		}else{
			win.params = params;
		}	
		win.show();					
	}
});
